package com.ycg.biquge.schedule;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ycg.biquge.pojo.Novel;
import com.ycg.biquge.service.NovelService;
import com.ycg.biquge.uitls.Crawler;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author YCG
 * @date 2024-05-12 20:07
 * @description 爬虫定时任务
 */
@Component("crawlerSchedule")
public class CrawlerSchedule {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private Crawler crawler;

    /**
     * 小说id
     */
    private static final AtomicInteger novelId = new AtomicInteger();

    /**
     * 每天凌晨4点执行
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void crawler() {
        System.out.println("开始爬取");
        String url = "https://www.bigee.cc/";
        // 可以直接启动 爬取数据
        Integer maxId;
        maxId = jdbcTemplate.queryForObject("select max(id) from novel", Integer.class);
        if (maxId == null) maxId = 0;
        novelId.set(maxId);
        // 爬取小说, 每天爬取一篇即可
        crawler.setUrl(url);
        crawler.setBookId(String.valueOf(novelId.intValue()));
        // 开始爬取
        crawler.crawl();
        // 修改最近更新的章节id和章节名称
        updateNewChapterInfo();
        // 计数加1
        novelId.incrementAndGet();
    }

    private void updateNewChapterInfo() {
        Integer id = novelId.intValue();
        Integer newChapterNum = jdbcTemplate.queryForObject("select max(num) from chapter where novel_id=?", Integer.class, id);
        // 根据章节号和小说号查询最大章节的id
        Integer newChapterId = jdbcTemplate.queryForObject("select id from chapter where novel_id=? and num = ?", Integer.class, id, newChapterNum);
        // 根据章节id查询标题
        String newChapterTitle = jdbcTemplate.queryForObject("select title from chapter where id= ?", String.class, newChapterId);
        // 根据小说id更新小说
        jdbcTemplate.update("update novel set new_id = ? and new_chapter = ? where id = ?", newChapterId, newChapterTitle, id);
    }

}
